package com.chagee.channel.server.config;


import com.alibaba.fastjson.support.spring.messaging.MappingFastJsonMessageConverter;
import lombok.SneakyThrows;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.stereotype.Component;

/**
 * @author: chang.jiawei
 * @date: 2024/02/20
 */
@Configuration
@Component
@RefreshScope
public class RocketMqConfig {

    @Value("${rocketmq-old.name-server}")
    private String oldNameServer;
    @Value("${rocketmq-old.producer.group}")
    private String oldGroup;
    @Value("${rocketmq-old.producer.access-key}")
    private String oldAccessKey;
    @Value("${rocketmq-old.producer.secret-key}")
    private String oldSecretKey;

    @Value("${rocketmq.name-server}")
    private String nameServer;
    @Value("${rocketmq.producer.group}")
    private String group;
    @Value("${rocketmq.producer.access-key}")
    private String accessKey;
    @Value("${rocketmq.producer.secret-key}")
    private String secretKey;

    @Bean
    public MessageConverter messageConverter() {
        // 使用 Jackson 进行 JSON 序列化
        return new MappingFastJsonMessageConverter();
    }

    @SneakyThrows
    @Bean(name = "oldProducer")
    public DefaultMQProducer oldProducer() {
        SessionCredentials sc = new SessionCredentials(oldAccessKey, oldSecretKey);
        RPCHook rpcHook = new AclClientRPCHook(sc);
        DefaultMQProducer producer = new DefaultMQProducer(oldGroup, rpcHook);
        producer.setNamesrvAddr(oldNameServer);
        return producer;
    }

    @Bean(name = "oldRocketMQTemplate")
    public RocketMQTemplate oldRocketMQTemplate() {
        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
        rocketMQTemplate.setProducer(oldProducer());
        return rocketMQTemplate;
    }

    @SneakyThrows
    @Bean(name = "newProducer")
    public DefaultMQProducer newProducer() {
        SessionCredentials sc = new SessionCredentials(accessKey, secretKey);
        RPCHook rpcHook = new AclClientRPCHook(sc);
        DefaultMQProducer producer = new DefaultMQProducer(group, rpcHook);
        producer.setNamesrvAddr(nameServer);
        return producer;
    }

    @Bean(name = "rocketMQTemplate")
    public RocketMQTemplate rocketMQTemplate() {
        RocketMQTemplate rocketMQTemplate = new RocketMQTemplate();
        rocketMQTemplate.setProducer(newProducer());
        return rocketMQTemplate;
    }


}
